import Vue from 'vue'
import store from './store'
import App from './App'

import textView from './components/textView.vue';
import itemList from './components/itemList.vue';
Vue.component('textView', textView);
Vue.component('itemList', itemList);

/* 全局注册QS-inputs-split组件 */
import QSInput from './components/QS-inputs-split/elements/QS-input/index.vue';
import QSRadio from './components/QS-inputs-split/elements/QS-radio/index.vue';
import QSCheckbox from './components/QS-inputs-split/elements/QS-checkbox/index.vue';
import QSTextarea from './components/QS-inputs-split/elements/QS-textarea/index.vue';
import QSKeyboardPlate from './components/QS-inputs-split/elements/QS-keyboard-plate/index.vue';
import QSPickerDate from './components/QS-inputs-split/elements/QS-picker-date/index.vue';
import QSPickerCity from './components/QS-inputs-split/elements/QS-picker-city/index.vue';
import QSPickerCustom from './components/QS-inputs-split/elements/QS-picker-custom/index.vue';
import QSPickerCustom2 from './components/QS-inputs-split/elements/QS-picker-custom2/index.vue';
import QSPics from './components/QS-inputs-split/elements/QS-pics/index.vue';
import QSInfinitePics from './components/QS-inputs-split/elements/QS-infinitePics/index.vue';
import QSwitch from './components/QS-inputs-split/elements/QS-switch/index.vue';
Vue.component('QSInput',QSInput);
Vue.component('QSRadio',QSRadio);
Vue.component('QSCheckbox',QSCheckbox);
Vue.component('QSTextarea',QSTextarea);
Vue.component('QSKeyboardPlate',QSKeyboardPlate);
Vue.component('QSPickerDate',QSPickerDate);
Vue.component('QSPickerCity',QSPickerCity);
Vue.component('QSPickerCustom',QSPickerCustom);
Vue.component('QSPickerCustom2',QSPickerCustom2);
Vue.component('QSPics',QSPics);
Vue.component('QSInfinitePics',QSInfinitePics);
Vue.component('QSwitch',QSwitch);


import * as filters from './filters'
import * as config from './config'

Object.keys(filters).forEach(key => {
	Vue.filter(key, filters[key])
})

//#ifdef H5
let jweixin = require('./components/jweixin-module')
let jwx = require('./components/jweixin-module/jwx')
Vue.mixin({
	onShow() {
		//jwx.configWeiXin(jwx => {})
	}
})
//#endif

const defConfig = config.def

const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

let userInfo = undefined

const logout = () => {
	userInfo = undefined
	uni.removeStorage({
		key: 'userInfo'
	})
}

const setUserInfo = (i) => {
	userInfo = i
}

const isVip = () => {
	return userInfo && userInfo.level
}

let loginLock = false

const request = (_url, data = {}, failCallback) => {
	//异步请求数据
	return new Promise(resolve => {
		if (!userInfo || !userInfo.accessToken) {
			userInfo = uni.getStorageSync('userInfo')
		}
		let token = userInfo ? userInfo.token : ''
		let baseUrl = config.def().baseUrl
		uni.request({
			url: baseUrl + _url,
			data: {
				...data
			},
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				// 'ACCESSTOKEN': accessToken,
				'Authorization': 'Bearer ' + token,
				//'content-type': 'application/json'
			},
			success: (res) => {
				//console.log(res);
				console.log(JSON.stringify(res));
				
				if (res.statusCode!= undefined && res.statusCode === 200) {
					if (res.data.code === 200 || res.data.code === 0) {
						resolve(res.data);
					} else if (res.data.code === 10001) {
						if (failCallback) {
							failCallback(res.data)
						}
						if (!loginLock) {
							loginLock = true
							uni.showModal({
								title: '登录提示',
								content: '您尚未登录，是否立即登录？',
								showCancel: true,
								confirmText: '登录',
								success: (e) => {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/public/login'
										})
									}
								},
								fail: () => {},
								complete: () => {
									loginLock = false
								}
							})
							
						}
					}else if (res.data.code === 1500) {
						//"message":"没有权限访问资源"
						//guns authtoken 过期
						uni.showModal({
							title: '登录提示',
							content: '您尚未登录，是否立即登录？',
							showCancel: true,
							confirmText: '登录',
							success: (e) => {
								if (e.confirm) {
									uni.navigateTo({
										url: '/pages/user/register'
									})
								}
							},
							fail: () => {},
							complete: () => {
								//loginLock = false
							}
						})
						
						
					}else {
						console.log("post faild...");
						if (failCallback) {
							failCallback(res.data)
						} else {
							uni.showToast({
								title: res.data.errmsg,
								icon: 'none'
							})
						}
					}
				}else{
					console.log("http net faild...");
					if (failCallback) {
						failCallback(res.data)
					} else {
						uni.showToast({
							title: res.data.errmsg,
							icon: 'none'
						})
					}
				}
			}
		})
	})
}

const uploadImg = (successCallback) => {
	let baseUrl = config.def().baseUrl
	uni.chooseImage({
		sizeType: ['compressed'],
		success: function(res) {
			for (let i = 0; i < res.tempFilePaths.length; i++) {
				uni.request({
					url: baseUrl + '/upload',
					method: 'get',
					success: function(signRes) {
						uni.showLoading({
							title: '图片上传中',
						})
						let fileName = ('imgs/' + random_string(15) + get_suffix(res.tempFilePaths[i]))
						uni.uploadFile({
							url: signRes.data.baseUrl,
							filePath: res.tempFilePaths[i],
							name: 'file',
							formData: {
								name: res.tempFilePaths[i],
								key: fileName,
								policy: signRes.data.policy,
								OSSAccessKeyId: signRes.data.accessid,
								success_action_status: '200',
								signature: signRes.data.signature
							},
							success: function(uploadRes) {
								uni.hideLoading()
								if (uploadRes.statusCode === 200) {
									if (successCallback) {
										successCallback(signRes.data.baseUrl + fileName)
									} else {
										uni.showToast({
											title: '上传成功',
											icon: 'none'
										})
									}
								} else {
									uni.hideLoading()
									uni.showToast({
										title: '网络错误 code=' + uploadRes.statusCode,
										icon: 'none'
									})
								}
							}
						})
					}
				})
			}
		}
	})
}


const isWeiXinBrowser = () => {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		
		return true
	} else {
		uni.showToast({
			title: '其他浏览器',
			icon: 'none'
		})
		return false
	}
	// #endif
	return false
}

const sleep= (time) =>{
  return new Promise((resolve) => setTimeout(resolve, time));
}

// 用法
// sleep(500).then(() => {
//     // 这里写sleep之后需要去做的事情
// })


// 把URL参数解析为一个对象
const urlParseParams= (urlStr) =>{
		// ?号后面的位置
		var pos = urlStr.indexOf('?') + 1;
		// 参数的字符串
		var paramsStr = urlStr.substring(pos);
		console.log(paramsStr);

		// 声明对象
		var obj = {};
		// 把参数添加到对象中
		var paramsArr = paramsStr.split('&');

		// 数组循环
		paramsArr.forEach( function(element) {
			// element == key0=aaa
			var _arr = element.split('=');
			// 往对象里添加内容
			obj[_arr[0]] =  _arr[1];			
		});
		// 返回对象
		return obj;
}

function get_suffix(filename) {
	var pos = filename.lastIndexOf('.')
	var suffix = ''
	if (pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix;
}

function random_string(len) {
	len = len || 32;
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	var maxPos = chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

const globalData = {}

Vue.config.productionTip = false
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$api = {
	msg,
	prePage,
	request,
	uploadImg,
	urlParseParams,
	logout,
	isVip,
	setUserInfo,
	defConfig,
	globalData,
	isWeiXinBrowser,
	sleep
};
//#ifdef H5
Vue.prototype.$jweixin = jweixin;
//#endif

App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()
